<template>
  <div class="_colle_warp" :style="scenceStyle">
    <div class="_colle_list" :style="scenceItemStyle" v-for="item in s.tools" :key="item.contract_address" @click="onSaleTool(item)">
      <div>
        <img :src="item.image" style="width: 100%" />
      </div>
      <div>
        <div>{{ item.name }}</div>
        <div>{{ item.count }}</div>
      </div>
    </div>
  </div>
  <div class="_home_warp">
    <div class="_cards" v-for="item in s.data" :key="item.id">
      <!--          <img src="" alt="">-->
      <div class="_card_img">
        <img :src="item.image" alt="" :style="imgStyle" />
      </div>
      <div class="_card_b">
        <div class="_card_xx">
          <div>{{ item.name }} #{{ item.num }}</div>
          <!--          <div>X50</div>-->
        </div>
        <div class="_card_rmb" @click="sale(item)">
          <div>Sale</div>
        </div>
        <div class="_card_rmb" @click="onTransfer(item)">
          <div>Transfer</div>
        </div>
      </div>
    </div>
  </div>

  <div v-if="!s.data || s.data.length === 0" class="empty">
    <img src="@/assets/empty@2x.png" alt="" />
  </div>

  <Dialog
    v-if="s.showSell"
    title="Sell"
    :close="close"
    :item="s.current"
    :allow="s.allow"
    :sell="doSale"
  ></Dialog>
  <Dialog
    v-if="s.showTransfer"
    title="Transfer"
    :close="close"
    :transfer="doTransfer"
  ></Dialog>
  <Dialog v-if="s.loading" title="Wait" :close="close"></Dialog>
</template>

<script setup>
import Dialog from "@/components/Dialog/Dialog.vue";
import { defineProps, ref } from "vue";
import {
  allowanceNFT,
  sell,
  getAddress,
  getBalance,
  approve,
  allowance,
  watch,
  transferFrom721,
  isApprovedForAll,
} from "../../../../dapp";
import {
  MARKET_ADDRESS,
  MGC_ADDRESS,
  CRA_ADDRESS,
  NFT_ADDRESS,
} from "../../../../abi";
import http from "../../../../http";
import { useRouter } from 'vue-router';

const router= useRouter();

var s = ref({
  showSell: false,
  showTransfer: false,
  current: null,
  data: [],
  tools: [],
  loading: false,
  allow: false,
});

function close() {
  console.log("close");
  s.value.showSell = false;
  s.value.showTransfer = false;
  s.value.loading = false;
}

async function sale(item) {
  console.log("sale=", item);
  s.value.current = item;
  s.value.showSell = true;
  s.value.allow = false;

  try {
    var current = s.value.current;
    var address = await getAddress();
    if (current.tp === "721") {
      const allow = await isApprovedForAll(address, current.type);
      console.log("allow=", allow);
      s.value.allow = allow;
    } else if (current.tp === "20") {
    }
  } catch (e) {
    console.log("ee", e);
  }
}

async function init() {
  var res = await http.get(`/api/nftlist`);
  // var res = {"code":200,"data":[{"attributes":null,"count":1,"description":"","id":100000337,"image_url":"https://mhyz1.oss-accelerate.aliyuncs.com/nftinfo/images/1.png","name":"","title":"","tp":"721"},{"attributes":null,"count":1,"description":"","id":100000230,"image_url":"https://mhyz1.oss-accelerate.aliyuncs.com/nftinfo/images/2.png","name":"","title":"","tp":"721"},{"attributes":null,"count":1,"description":"","id":100000223,"image_url":"https://mhyz1.oss-accelerate.aliyuncs.com/nftinfo/images/1.png","name":"","title":"","tp":"721"}],"msg":"OK","tools":[{"contract_address":"0xfed183FE03c7d600520dCea11c41484B31FFb1d9","count":100000000,"image_url":"https://mhyz1.oss-accelerate.aliyuncs.com/nftinfo/images/0xfed183FE03c7d600520dCea11c41484B31FFb1d9.png","name":"POTION","tp":"20"},{"contract_address":"0xcAc079cc69175827D4472f7eB418A5578eC3a45C","count":100000000,"image_url":"https://mhyz1.oss-accelerate.aliyuncs.com/nftinfo/images/0xcAc079cc69175827D4472f7eB418A5578eC3a45C.png","name":"Box","tp":"20"}]}
  if (res.code === 200) {
    console.log(res.data);
    s.value.data = res.data;
    s.value.tools = res.tools;
  }
}

var submit = false;

async function doSale(input, mType, num) {
  if (submit) {
    return;
  }
  submit = true;
  // console.log('sale=', s.value.current, input, mType)
  var current = s.value.current;
  if (current.tp === "721") {
    await _sellNft(input, mType, num);
  } else if (current.tp === "20") {
    await _sellErc(input, mType, num);
  }

  submit = false;
  s.value.loading = false;
  // 返回上一页
  router.back()
  // Returned error: unknown account
  // await sell(MARKET_ADDRESS, )
  // _currency是用什么货币买，传cra或者mgc的tokenAddress。bnb的话传0地址。_iserc是否为道具商品，1是道具，0是nft
}

async function _sellNft(input, mType, num) {
  try {
    var curr;
    if (mType === "BNB") {
      curr = "0x0000000000000000000000000000000000000000";
    } else if (mType === "MGC") {
      curr = MGC_ADDRESS;
    } else if (mType === "CRA") {
      curr = CRA_ADDRESS;
    } else {
      throw Error("err curr");
    }
    console.log("sell", input, mType, curr);
    var current = s.value.current;
    var address = await getAddress();

    if (!s.value.allow) {
      s.value.loading = true;
      const allowTxid = await allowanceNFT(address, current.type);
      s.value.allow = true;
      console.log("allowTxid=", allowTxid);
      async function sleep() {
        return new Promise((resolve) => {
          setTimeout(resolve, 3000);
        });
      }
      await sleep();
      return;
    }

    const item = s.value.current
    const txid = await sell(current.id, NFT_ADDRESS, input, curr, 0, item.type);
    s.value.showSell = false;
    // Toast('Submit')
    console.log("txid=", txid);
    console.log("wait tx confirm");
    s.value.loading = true;
    await watch(txid);
    await http.get(`/api/sync?txid=${txid}`);
    console.log("tx was confirm");
    init();
  } catch (e) {
    console.log("e=", e);
  }
}

async function _sellErc(input, mType, num) {
  try {
    var curr;
    if (mType === "BNB") {
      curr = "0x0000000000000000000000000000000000000000";
    } else if (mType === "MGC") {
      curr = MGC_ADDRESS;
    } else if (mType === "CRA") {
      curr = CRA_ADDRESS;
    } else {
      throw Error("err curr");
    }
    console.log("sell", input, num, mType, curr);
    var current = s.value.current;
    var address = await getAddress();
    var balance = await getBalance(current.contract_address, address);
    console.log("balance=", balance);
    if (balance < num) {
      Toast("Insufficient available");
      throw Error("Insufficient available");
    }
    var allowBalance = await allowance(current.contract_address, address, current.type);
    console.log("allowBalance=", allowBalance);
    var value = "0x" + (num * 1).toString(16);
    console.log("approve", value);
    if (allowBalance < num) {
      var tt = await approve(current.contract_address, value, current.type);
      console.log("approve hash=", tt);
      console.log("wait");
      s.value.loading = true;
      await watch(tt);
      console.log("approve success");
    }

    const item = s.value.current
    const txid = await sell(value, current.contract_address, input, curr, 1, item.type);
    s.value.showSell = false;
    // Toast('Submit')
    console.log("txid=", txid);
    console.log("wait tx confirm");
    s.value.loading = true;
    await watch(txid);
    await http.get(`/api/sync?txid=${txid}`);
    console.log("tx was confirm");
    init();
  } catch (e) {
    console.log("e=", e);
  }
}

async function onTransfer(item) {
  s.value.current = item;
  s.value.showTransfer = true;
}

async function doTransfer(num, toAddress) {
  // console.log('tran=', num, address)
  if (submit) {
    return;
  }
  submit = true;
  try {
    if (
      !toAddress ||
      toAddress.indexOf("0x") === -1 ||
      toAddress.length !== 42
    ) {
      s.value.showTransfer = false;
      Toast("Invalid Address");
      throw new Error("Invalid Address");
    }
    var current = s.value.current;
    var address = await getAddress();
    console.log("transferFrom", address, toAddress, current.id);
    const txid = await transferFrom721(address, toAddress, current.id);
    s.value.showTransfer = false;
    // Toast('Submit')
    console.log("txid=", txid);
    console.log("wait tx confirm");
    s.value.loading = true;
    await watch(txid);
    // await http.get(`/api/sync?txid=${txid}`)
    console.log("tx was confirm");
    init();
  } catch (e) {
    console.log("e=", e);
  }
  submit = false;
  s.value.loading = false;
}

async function onSaleTool(item) {
  s.value.current = item;
  console.log("onSaleTool=", item);
  s.value.showSell = true;
}

init();
</script>


<script>
export default {
  computed: {
    imgStyle() {
      return document.body.clientWidth <= 750
        ? {
            height: "100vw",
            maxWidth: "350px",
            maxHeight: "350px",
          }
        : {
            height: "243px",
          };
    },
    scenceStyle() {
      return document.body.clientWidth <= 750
        ? {
            alignItems: "center",
            justifyContent: "spaceBetween",
          }
        : {
            display: "flex",
            justifyContent: 'start',
            overflowX: 'auto',
          };
    },
    scenceItemStyle() {
      return  document.body.clientWidth <= 750? {
        'width': '100%',
      }: {
        'width': '290px',
        marginRight: '30px',
      };
    }
  },
};
</script>

<style scoped lang="scss">
._colle_warp {
  align-items: center;
  justify-content: space-between;
}
._colle_list {
  padding: 13px 0 10px 8px;
  border-radius: 1px;
  border: 1px solid #d9d9d9;
  display: flex;
  margin-top: 15px;
  cursor: pointer;
  > div {
    &:nth-child(1) {
      width: 50px;
      height: 50px;
      background-color: #c5c5c5;
    }
    &:nth-child(2) {
      font-size: 14px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #3a3a3a;
      margin-left: 11px;
    }
  }
}
._home_warp {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-column-gap: 107px;
  grid-row-gap: 30px;
  margin-top: 60px;
}
._cards {
  border: 1px solid #d9d9d9;
}
._card_img {
  width: 100%;
  padding: 15px 0px;
  text-align: center;
}
._card_b {
  padding: 0 18px 30px 18px;
}
._card_xx {
  display: flex;
  align-items: center;
  margin-top: 18px;
  padding-bottom: 14px;
  border-bottom: 1px solid #d9d9d9;
  margin-bottom: 30px;
  > div {
    &:nth-child(1) {
      font-size: 20px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #393939;
    }
    &:nth-child(2) {
      font-size: 12px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #fdb919;
      width: 40px;
      height: 20px;
      background: rgba(249, 178, 7, 0.33);
      border-radius: 10px;
      border: 1px solid #fdb71c;
      text-align: center;
      line-height: 20px;
      margin-left: 2px;
    }
  }
}
._card_rmb {
  width: 100%;
  background: #fcc33c;
  border-radius: 1px;
  height: 26px;
  font-size: 14px;
  font-family: PingFangSC-Semibold, PingFang SC;
  font-weight: 600;
  color: #383838;
  line-height: 26px;
  text-align: center;
  margin-top: 13px;
  cursor: pointer;
}
.empty {
  width: 100%;
  /* margin: 0 auto; */
  display: flex;
  align-items: center;
  justify-content: center;
  img {
    width: 388px;
    height: 320px;
  }
}

@media screen and (max-width: 750px) {
  ._home_warp {
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    /*padding: 20px;*/
    /*overflow: hidden;*/
    /*padding: 0*/
  }
}
</style>
